package com.geek.service.impl;

import com.github.pagehelper.PageHelper;
import com.geek.bean.PageData;
import com.geek.mapper.MarketCartMapper;
import com.geek.mapper.MarketCouponMapper;
import com.geek.mapper.MarketCouponUserMapper;
import com.geek.model.*;
import com.geek.service.CouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CouponUserServiceImpl implements CouponUserService {
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCartMapper cartMapper;
    //mylist
    @Override
    public PageData list(Integer userId, Integer status, Integer page, Integer limit) {
        //根据userId查询couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId)
                .andStatusEqualTo(status.shortValue())
                .andDeletedEqualTo(false);
        couponUserExample.setOrderByClause("add_time desc");
        PageHelper.startPage(page,limit);
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        PageData data = PageData.list(couponUsers);
        List<Map> mapList = couponUsers.stream().map(marketCouponUser -> {
            Map<String, Object> map = new HashMap<>();
            //根据couponId查询coupon
            Integer couponId = marketCouponUser.getCouponId();
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponId);
            if (marketCoupon != null) {
                map.put("available", false);
                map.put("cid", marketCoupon.getId());
                map.put("desc", marketCoupon.getDesc());
                map.put("discount", marketCoupon.getDiscount());
                map.put("endTime", marketCoupon.getEndTime());
                map.put("id", marketCouponUser.getId());
                map.put("min", marketCoupon.getMin());
                map.put("name", marketCoupon.getName());
                map.put("startTime", marketCoupon.getStartTime());
                map.put("tag", marketCoupon.getTag());
            }
            return map;
        }).collect(Collectors.toList());
        data.setList(mapList);
        return data;
    }

    @Override
    public int insert(Integer userId, Integer couponId) {
        //根据couponId查询coupon
        MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponId);
        Integer total = marketCoupon.getTotal();
        //total > 0 优惠卷减一
        if (total > 0){
            //若total！=0，优惠卷不是无限的，数量减一
            MarketCouponExample couponExample = new MarketCouponExample();
            couponExample.createCriteria().andIdEqualTo(couponId);
            MarketCoupon coupon = new MarketCoupon();
            int a = 1;
            //如果total只剩一张
            if (total == 1){
                //将total变成-1
                a = 2;
            }
            coupon.setTotal(total - a);
            couponMapper.updateByExampleSelective(coupon,couponExample);
        }
        if (total == 0){
            Date current = new Date();
            //插入数据
            MarketCouponUser couponUser = MarketCouponUser.builder()
                    .userId(userId)
                    .couponId(couponId)
                    .status((short) 0)
                    .usedTime(null)
                    .startTime(marketCoupon.getStartTime())
                    .endTime(marketCoupon.getEndTime())
                    .orderId(null)
                    .addTime(current)
                    .updateTime(current)
                    .deleted(false)
                    .build();
            couponUserMapper.insert(couponUser);
        }
        if (total < 0){
            return 0;
        }
            return 1;
    }

    @Override
    public boolean isList(Integer id, Integer userId,short limit) {
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andCouponIdEqualTo(id);
        List<MarketCouponUser> marketCouponUsers = couponUserMapper.selectByExample(couponUserExample);
        if (marketCouponUsers.size() < limit){
            return false;
        }
        return true;
    }

    //selectlist
    public List<Map> list(Integer userId, Integer status,Integer cartId) {
        //根据cartId查询商品
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.createCriteria().andDeletedEqualTo(false)
                .andCheckedEqualTo(true)
                .andUserIdEqualTo(userId);
        List<MarketCart> cartList = cartMapper.selectByExample(cartExample);
        BigDecimal allPrice = cartList.stream().map(marketCart -> {
            BigDecimal price = marketCart.getPrice();
            Short number = marketCart.getNumber();
            return price.multiply(BigDecimal.valueOf(number));
        }).reduce(BigDecimal.ZERO, BigDecimal::add);
        //根据userId查询couponId
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.createCriteria().andUserIdEqualTo(userId)
                .andStatusEqualTo(status.shortValue())
                .andDeletedEqualTo(false);
        List<MarketCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
        List<Map> mapList = couponUsers.stream().map(marketCouponUser -> {
            Map<String, Object> map = new HashMap<>();
            //根据couponId查询coupon
            Integer couponId = marketCouponUser.getCouponId();
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponId);
            if (marketCoupon != null) {
                Short goodsType = marketCoupon.getGoodsType();
                //如果满足优惠卷需求为true
                if (allPrice.compareTo(marketCoupon.getMin()) > 0) {
                    map.put("available", true);
                } else {
                    //不满足优惠卷则为false
                    map.put("available", false);
                }
                map.put("cid", marketCoupon.getId());
                map.put("desc", marketCoupon.getDesc());
                map.put("discount", marketCoupon.getDiscount());
                map.put("endTime", marketCoupon.getEndTime());
                map.put("id", marketCouponUser.getId());
                map.put("min", marketCoupon.getMin());
                map.put("name", marketCoupon.getName());
                map.put("startTime", marketCoupon.getStartTime());
                map.put("tag", marketCoupon.getTag());
            }
            return map;
        }).collect(Collectors.toList());
        return mapList;
    }
    @Override
    public void updateCouponStatus(Integer userId, Integer couponId) {
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andUserIdEqualTo(userId)
                .andCouponIdEqualTo(couponId);
        List<MarketCouponUser> marketCouponUsers = couponUserMapper.selectByExample(example);
        marketCouponUsers.get(0).setStatus((short) 1);

        couponUserMapper.updateByPrimaryKeySelective(marketCouponUsers.get(0));
    }
}
